package com.mxl.service.channel;

import java.io.IOException;
import java.net.SocketTimeoutException;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.mxl.common.HttpClientUtil;
import com.mxl.dao.channel.model.DealRequest;
import com.mxl.dao.channel.model.DealResponse;

/**
 * 
 * @author mxl
 * 
 */
public class CommChannelAccessor implements ChannelAccessor {

	private static Logger logger = LoggerFactory
			.getLogger(CommChannelAccessor.class);

	private DealRequestWrapper commDealRequestWrapper;

	public void setCommDealRequestWrapper(
			DealRequestWrapper commDealRequestWrapper) {
		this.commDealRequestWrapper = commDealRequestWrapper;
	}

	public DealResponse sendRequest(DealRequest request) {
		CommChargeResponse chargeResponse = new CommChargeResponse();
		try {
			String httpUrl = request.getReqContentval();
			logger.info("the card charge url is : {}", httpUrl);
			byte[] chargeResult = HttpClientUtil.postDealRequest(httpUrl);
			if (chargeResult != null) {
				commDealRequestWrapper.resolveCardResponse(chargeResponse,
						chargeResult);
			}
		} catch (SocketTimeoutException e) {
			logger
					.error(
							"card channel charge http happen some exception, exception is : ",
							e);
			commDealRequestWrapper.resolverTimeout(chargeResponse);
		} catch (IOException e) {
			logger
					.error(
							"card channel charge IO happen some exception, exception is : ",
							e);
			commDealRequestWrapper.resolverTimeout(chargeResponse);
		} catch (Exception e) {
			logger
					.error(
							"card channel charge happen some exception, exception is : ",
							e);
			commDealRequestWrapper.resolverTimeout(chargeResponse);
		}

		return commDealRequestWrapper.buildDealResponse(chargeResponse);
	}
}
